<script lang="ts">
    import type { Todo } from "$lib/types/todo";

    interface Props {
        todos: Todo[];
        active: boolean;
    }

    const { todos, active }: Props = $props();

    const handleCheckboxChange = (event: Event) => {
        const target = event.target as HTMLInputElement;
        if (target.form) {
            target.form.submit();
        }
    };
</script>

{#if todos.length === 0}
    <div class=" text-gray-300 text-4xl mt-30">Nothing here ...</div>
{:else}
    <div class="space-y-3">
        {#each todos as todo (todo.id)}
            <form method="POST" action="?/finish">
                <label
                    for={String(todo.id)}
                    class="flex cursor-pointer items-start gap-4 rounded-lg border border-gray-300 p-4 transition hover:bg-gray-100"
                >
                    <div class="hidden">
                        <input type="text" name="Id" value={todo.id} />
                    </div>
                    <div class="flex items-center">
                        &#8203;
                        <input
                            type="checkbox"
                            class="size-4 rounded"
                            id={String(todo.id)}
                            checked={!active}
                            disabled={!active}
                            onchange={handleCheckboxChange}
                        />
                    </div>

                    <div>
                        <strong
                            class="font-medium"
                            class:line-through={!active}
                        >
                            {todo.title}
                        </strong>

                        <p class="mt-1 text-pretty text-sm text-gray-500">
                            {todo.create_at}
                        </p>
                    </div>
                </label>
            </form>
        {/each}
    </div>
{/if}
